/**
 * 
 */
package com.p2p.backend.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.alibaba.fastjson.JSONObject;
import com.p2p.backend.service.BackIdcardService;
import com.p2p.backend.service.ExportService;
import com.p2p.base.annotation.PermissionNeed;
import com.p2p.base.page.PageVo;
import com.p2p.base.util.BasePropertyConfigurer;
import com.p2p.base.util.DateUtil;
import com.p2p.base.util.Encrypter;
import com.p2p.base.util.LoginToken;
import com.p2p.base.web.controller.BaseController;
import com.p2p.front.dal.model.BorrowerPhoto;
import com.p2p.front.dal.model.IdCardInfo;
import com.p2p.front.dal.model.User;
import com.p2p.front.dal.model.UserInfoAuth;
import com.p2p.front.enums.PhotoType;
import com.p2p.front.service.BorrowerPhotoService;
import com.p2p.front.service.IdCardService;
import com.p2p.front.service.MemberPointService;
import com.p2p.front.service.TenderAmountSumService;
import com.p2p.front.service.UserInfoAuthService;
import com.p2p.front.service.UserInfoService;
import com.p2p.front.service.UserRegisterService;
import com.p2p.front.service.UserService;
import com.p2p.front.util.ValidateUtil;
import com.p2p.front.vo.UserInfoVO;
import com.p2p.front.vo.UserRegisterVo;
import com.p2p.trans.client.facade.AccountQueryFacade;
import com.p2p.user.enums.UserInfoName;
import com.p2p.user.facade.UserQueryFacade;

/**
 * @author ruiqi
 *
 */
@Controller
public class UserController extends BaseController{

	List<UserInfoName> personalInfoNameList;

	List<UserInfoName> jobInfoNameList;

	List<UserInfoName> contactInfoNameList;

	@Resource
	UserService userService;

	@Resource
	UserInfoService userInfoService;

	@Resource
	UserInfoAuthService userInfoAuthService;

	@Resource
	UserQueryFacade userQueryFacade;

	@Resource
	private IdCardService idCardService;
	@Resource
	private BackIdcardService backIdcardService;

	@Resource
	private BorrowerPhotoService borrowerPhotoService;

	@Resource
	private AccountQueryFacade remoteAccountQueryFacade;

	@Resource
	private MemberPointService memberPointService;

	@Resource
	private UserRegisterService userRegisterService;
	
	@Resource
	private TenderAmountSumService tenderAmountSumService;

	@Resource
	private ExportService exportService;
	
	public UserController() {
		init();
	}

	@PermissionNeed("user_search")
	@RequestMapping("/searchUser")
	public void searchUser(String search, Model model) {
		if (StringUtils.isBlank(search)) {
			model.addAttribute("res", 0);
			model.addAttribute("msg", " blank search condition ");
			return;
		}
		User user = userService.searchUser(search);
		model.addAttribute("res", 1);
		Map<String, Object> data = new HashMap<String, Object>();
		model.addAttribute("data", data);
		if (user != null) {
			List<Map<String, Object>> queryList = new ArrayList<Map<String, Object>>();
			data.put("rows", queryList);
			data.put("totalCount", 1);
			Map<String, Object> oneUser = new HashMap<String, Object>();
			queryList.add(oneUser);
			UserInfoVO userInfoVo = userInfoService.findByNameEnums(
					user.getUid(), Arrays.asList(UserInfoName.values()));
			oneUser.put("user", user);
			oneUser.put("userInfo", userInfoVo.getInfoMap());
		}
	}

	@PermissionNeed("user_search")
	@RequestMapping("/searchBaseUser")
	public void searchBaseUser(String search, int page, int rows, Model model) {
		model.addAttribute("res", 1);
		Map<String, Object> data = new HashMap<String, Object>();
		model.addAttribute("data", data);
		List<User> queryList = new ArrayList<User>();
		if (StringUtils.isBlank(search)) {
			// model.addAttribute("res", 0);
			/*
			 * model.addAttribute("msg", " blank search condition ");
			 * data.put("rows", queryList); data.put("total", 1); return;
			 */
			search = "1";
		}
		PageVo pageVo = new PageVo();
		pageVo.setPageNum(page);
		pageVo.setPageSize(rows);
		PageVo searchListPage = userService.searchUserListPage(search, pageVo);
		searchListPage = userService.buildForExtraInfo(pageVo);
		/*List<String> accountNoList = new ArrayList<String>();
		List<String> userIdList = new ArrayList<String>();
		for (User user : (List<User>) searchListPage.getList()) {
			String accountNo = user.getAccountNo();
			if (StringUtils.isNotBlank(accountNo)) {
				accountNoList.add(accountNo);
			}
			String userId = user.getUid();
			userIdList.add(userId);
		}
		// 查询资金状态
		AccountQueryResult queryResult = remoteAccountQueryFacade
				.batchQueryAccountInfo(accountNoList);

		Map<String, MemberPoint> memberPointMap = memberPointService
				.queryByUserIdList(userIdList);
		
		Map<String,UserCredits>  totalTenderAmountMap = tenderAmountSumService.getUserTenderTatalAmount(userIdList);
		// Map<String,MemberPoint> memberPointMap = new
		// HashMap<String,MemberPoint>();
		List<Map<String, Object>> viewList = new ArrayList<Map<String, Object>>();
		if (queryResult.isSuccess()) {
			Map<String, AccountVO> accountVOmap = queryResult.getAccountVOMap();
			for (User user : (List<User>) searchListPage.getList()) {
				String accountNo = user.getAccountNo();
				String userId = user.getUid();
				Map<String, Object> usermodel = getViewModel(user,
						accountVOmap.get(accountNo), memberPointMap.get(userId),totalTenderAmountMap.get(userId));
				viewList.add(usermodel);
			}
		}*/
		
		data.put("rows", searchListPage.getList());
		data.put("total", searchListPage.getTotalCount());

	}

	@PermissionNeed("user_search")
	@RequestMapping("/searchUserMobile")
	public void searchUserMobile(String search, Model model) {
		model.addAttribute("res", 1);
		Map<String, Object> data = new HashMap<String, Object>();
		model.addAttribute("data", data);

		if (StringUtils.isBlank(search)) {
			// model.addAttribute("res", 0);
			/*
			 * model.addAttribute("msg", " blank search condition ");
			 * data.put("rows", queryList); data.put("total", 1); return;
			 */
			search = "1";
		}
		List<User> userList = userService.searchUserList(search);
		StringBuilder sb = new StringBuilder();
		for (User user : userList) {
			if (StringUtils.isNotBlank(user.getUmobile())) {
				sb.append(user.getUmobile() + ",");
			}
		}
		sb.deleteCharAt(sb.length() - 1);

		data.put("userMobiles", sb.toString());

	}
	
	@RequestMapping("/doExportUser")
	public void doExportSuccese(PageVo form,HttpServletResponse response){
		
		//JSONObject json = new JSONObject();
		/*if(StringUtils.isBlank(form.getStartDate())||StringUtils.isBlank(form.getEndDate())){
			this.returnMessage(response, "开始结束时间不能为空");
			return;
		}*/
		
		
		 try {
			response.setHeader("Content-Disposition", "attachment;filename=" + new String(("会员信息").getBytes(), "ISO-8859-1"));
			//设定输出文件头
			   response.setContentType("application/vnd.ms-excel;charset=UTF-8");// 定义输出类型 
			   // 通过response的输出流把工作薄的流发送浏览器形成文件
			   OutputStream outStream = response.getOutputStream();
			   exportService.exportAllUser(outStream, form);
			   return;
		 } catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		 //失败或者异常
		 JSONObject jsonObject = new JSONObject();
			jsonObject.put("res", -1);
		this.returnJsonObject(response, jsonObject);
		return;
	}

	/*
	 * {field:'uid',title:'uid'}, {field:'uname',title:'用户名'},
	 * {field:'umobile',title:'电话'}, {field:'uemail',title:'邮箱'},
	 * {field:'accountNo',title:'资金帐号'}
	 */
	/*private Map<String, Object> getViewModel(User user, AccountVO accountVO,
			MemberPoint memberPoint,UserCredits userCredits) {
		Map<String, Object> model = new HashMap<String, Object>();
		model.put("uid", user.getUid());
		model.put("uname", user.getUname());
		model.put("realname", user.getRealname());
		model.put("umobile", user.getUmobile());
		model.put("uemail", user.getUemail());
		model.put("accountNo", user.getAccountNo());
		if (accountVO != null) {
			model.put("balance", accountVO.getBalance().toString());
			model.put("freeze", accountVO.getFreezeAmount().toString());
			model.put("canUseBalance", accountVO.getCanUserBalance().toString());
		}
		if (memberPoint != null) {
			model.put("produceCumulative", memberPoint.getProduceCumulative());
			model.put("canUsedPoint", memberPoint.getCanUsedPoint());
			model.put("level", memberPoint.getLevel());
		}
		if(userCredits!=null){
			Money m = new Money(userCredits.getValue());
			model.put("totalTenderAmount", m.toString());
		}
		return model;

	}*/

	@RequestMapping("/showUserInfo")
	public String showUserInfo(String uid, Model model) {

		model.addAttribute("res", 1);
		Map<String, Object> data = new HashMap<String, Object>();
		model.addAttribute("data", data);

		UserInfoVO userInfoVo = userInfoService.findByNameEnums(uid,
				Arrays.asList(UserInfoName.values()));

		HashMap<String, Integer> tempMap = new HashMap<String, Integer>();
		for (UserInfoName userInfoName : UserInfoName.values()) {
			if (userInfoName.getAuthIndex() != null) {
				tempMap.put(userInfoName.name(), userInfoName.getAuthIndex());
			}
		}

		Map<Integer, Character> userAuthMap = userInfoAuthService
				.getAuthNameKeyList(uid, tempMap.values());

		Map<String, Character> authMap = new HashMap<String, Character>();
		for (Map.Entry<String, Integer> entry : tempMap.entrySet()) {
			Integer value = entry.getValue();
			if (userAuthMap.get(value) != null) {
				authMap.put(entry.getKey(), userAuthMap.get(value));
			}

		}

		data.put("infoMap", userInfoVo.getInfoMap());
		data.put("authMap", authMap);
		UserInfoAuth userInfoAuth = userInfoAuthService.getUserAuth(uid);
		data.put("authStr", userInfoAuth.getAuthValue());
		data.put("userId", uid);
		data.put("personalInfoNameList", personalInfoNameList);
		data.put("jobInfoNameList", jobInfoNameList);
		data.put("contactInfoNameList", contactInfoNameList);

		return "user/showUserInfo";
	}

	@RequestMapping("/info/saveInfo")
	public String saveInfo(UserInfoVO userInfoVO, Model model) {

		userInfoService.batchSave(userInfoVO);
		Map<String, Character> authMap = userInfoVO.getAuthMap();
		TreeMap<Integer, Character> userAuthMap = new TreeMap<Integer, Character>();
		for (UserInfoName userInfoName : UserInfoName.values()) {
			if (userInfoName.getAuthIndex() != null) {
				if (authMap.get(userInfoName.name()) != null) {
					userAuthMap.put(userInfoName.getAuthIndex(),
							authMap.get(userInfoName.name()));
				}
			}
		}
		userInfoAuthService.saveAuthByValueMap(userInfoVO.getUserId(),
				userAuthMap);
		model.addAttribute("res", 1);
		return "userInfo/saveSuccess";
	}

	private void init() {
		personalInfoNameList = new ArrayList<UserInfoName>();

		personalInfoNameList.add(UserInfoName.GENDER);
		personalInfoNameList.add(UserInfoName.BIRTHDATE);// 出生日期
		personalInfoNameList.add(UserInfoName.IDCARD_PROVINCE);// 户籍省份
		personalInfoNameList.add(UserInfoName.IDCARD_CITY);// 户籍城市
		personalInfoNameList.add(UserInfoName.PROVINCE);// 省份
		personalInfoNameList.add(UserInfoName.CITY);// 城市
		personalInfoNameList.add(UserInfoName.DISTRICT);// 区域
		personalInfoNameList.add(UserInfoName.ADDRESS);// 详细居住地址
		personalInfoNameList.add(UserInfoName.ADDRESS_PHONE);// 居住地电话
		personalInfoNameList.add(UserInfoName.EDUCATION);// 学历:0-未知);1-高中或以下);2-大专);3-本科);4-研究生或以上
		personalInfoNameList.add(UserInfoName.GRADUATED_YEAR);// 毕业年份
		personalInfoNameList.add(UserInfoName.GRADUATED_SCHOOL);// 毕业学校
		personalInfoNameList.add(UserInfoName.MARRIAGE);// 婚姻状况:0-未知);1-已婚);2-离异);3-未婚
		personalInfoNameList.add(UserInfoName.HAVE_CHILD);// 有无子女:0-未知);1-有);2-无
		personalInfoNameList.add(UserInfoName.HAVE_HOUSE);// 住房情况:0-未知);1-无);2-商品房);3-自建房
		personalInfoNameList.add(UserInfoName.HOUSE_LOAN);// 有无房贷:0-未知);1-有);2-无
		personalInfoNameList.add(UserInfoName.HAVE_CAR);// 是否有车:0-未知);1-有);2-无
		personalInfoNameList.add(UserInfoName.CAR_BRAND);// 汽车品牌
		personalInfoNameList.add(UserInfoName.CAR_YEAR);// 购车年份
		personalInfoNameList.add(UserInfoName.CAR_LOAN);// 有无车贷:0-未知);1-有);2-无

		jobInfoNameList = new ArrayList<UserInfoName>();

		jobInfoNameList.add(UserInfoName.JOB_COMPANY);// 单位名称或个人
		jobInfoNameList.add(UserInfoName.JOB_TYPE);// 工作类型: 0-未知,
													// 1-工薪阶层,2-私营企业主,3-自由职业,4-网络商家,5-其他
		jobInfoNameList.add(UserInfoName.JOB_COMPANY_TYPE);// 公司类别
		jobInfoNameList.add(UserInfoName.JOB_COMPANY_SCALE);// 公司规模
		jobInfoNameList.add(UserInfoName.JOB_INDUSTRY);// 行业
		jobInfoNameList.add(UserInfoName.JOB_TITLE);// 职位
		jobInfoNameList.add(UserInfoName.JOB_SALARY);// 月收入
		jobInfoNameList.add(UserInfoName.JOB_YEARS);// 工作年限
		jobInfoNameList.add(UserInfoName.JOB_EMAIL);// 工作邮箱
		jobInfoNameList.add(UserInfoName.JOB_PROVINCE);// 工作省份
		jobInfoNameList.add(UserInfoName.JOB_CITY);// 工作城市
		jobInfoNameList.add(UserInfoName.JOB_COMPANY_ADDRESS);// 公司地址
		jobInfoNameList.add(UserInfoName.JOB_COMPANY_PHONE);// 公司电话

		contactInfoNameList = new ArrayList<UserInfoName>();
		contactInfoNameList.add(UserInfoName.FAMILY_NAME);// 亲属姓名
		contactInfoNameList.add(UserInfoName.FAMILY_WHO);// 关系
		contactInfoNameList.add(UserInfoName.FAMILY_PHONE);// 亲属联系人手机或电话
		contactInfoNameList.add(UserInfoName.OTHER_NAME);// 其它联系人姓名
		contactInfoNameList.add(UserInfoName.OTHER_WHO);// 关系
		contactInfoNameList.add(UserInfoName.OTHER_PHONE);// 其它联系人手机或电话

	}

	@RequestMapping("/idcard_list")
	public void getIdCard(PageVo form, Model model) {
		model.addAttribute("res", 1);
		Map<String, Object> data = new HashMap<String, Object>();
		model.addAttribute("data", data);
		PageVo idcard = idCardService.listAll(form);
		
		//无语了，身份认证信息，用贷款的模型封装
		List<IdCardInfo> idCardList = (List<IdCardInfo>)idcard.getList();
		List<String> uidList = new ArrayList<String>();
		for(IdCardInfo idCardInfo:idCardList){
			uidList.add(idCardInfo.getUid());
		}
		
		Map<String, User> userMap = userService.searchUserByIdList(uidList);
		for(IdCardInfo idCardInfo:idCardList){
			idCardInfo.setUmobile(userMap.get(idCardInfo.getUid()).getUmobile());
		}
		model.addAttribute("data", data);
		data.put("rows", idCardList);
		data.put("total", idcard.getTotalCount());
	}

	@PermissionNeed("user_idcard_audit")
	@RequestMapping("/editIdCardStatus")
	public String editIdCardStatus(@RequestParam String uid, Model model) {
		IdCardInfo idCard = idCardService.getAuthing(uid);

		List<BorrowerPhoto> idCardPhotoList = borrowerPhotoService.findByUid(
				Long.valueOf(uid), PhotoType.IDCARD.getCode());
		/*
		 * List<BorrowerPhoto> idCardPhotoList = new ArrayList<BorrowerPhoto>();
		 * for(BorrowerPhoto bp : borrowerPhotoList){
		 * if(bp.getUrl().contains("idCard/")){ idCardPhotoList.add(bp); } }
		 */
		model.addAttribute("idCard", idCard);
		model.addAttribute("idCardPhotoList", idCardPhotoList);
		return "user/editIdCardStatus";
	}

	@PermissionNeed("user_idcard_audit")
	@RequestMapping("/saveIdCardStatus")
	public void saveIdCardStatus(@RequestParam String uid,
			@RequestParam int status) {
		IdCardInfo idCard = idCardService.getAuthing(uid);
		if (idCard != null) {
			idCard.setStatus(status);
			backIdcardService.authIdCard(idCard);
		}
	}

	@RequestMapping(value = "/handworkRegisterUser", method = RequestMethod.POST)
	public String doRegisterByMobile(String uname, String umobile,
			String password, Model model) {
		if (StringUtils.isBlank(uname) || StringUtils.isBlank(umobile)
				|| StringUtils.isBlank(password)) {
			model.addAttribute("errInfo_exist", "必填信息不能为空");
			model.addAttribute("uname", uname);
			model.addAttribute("umobile", umobile);
			model.addAttribute("password", password);
			return "register/register";
		}

		Boolean validateMobile = ValidateUtil.isPhone(umobile);
		if (!validateMobile) {
			model.addAttribute("errInfo_exist", "手机号码格式不正确 *");
			model.addAttribute("uname", uname);
			model.addAttribute("umobile", umobile);
			model.addAttribute("password", password);
			return "register/register";
		}
		User user = userService.findByPhone(umobile);
		if (user != null && user.getUmobile() != null) {
			model.addAttribute("errInfo_exist", "手机已经注册 *");
			model.addAttribute("uname", uname);
			model.addAttribute("umobile", umobile);
			model.addAttribute("password", password);
			return "register/register";
		}
		// 注册的时候，不再需要用户名
		User unameUser = userService.findByUname(uname);
		if (unameUser != null && unameUser.getUname() != null) {
			model.addAttribute("errInfo_uname_exist", "用户名已经存在");
			model.addAttribute("uname", uname);
			model.addAttribute("umobile", umobile);
			model.addAttribute("password", password);
			return "register/register";
		}

		UserRegisterVo userRegisterVo = new UserRegisterVo();
		userRegisterVo.setUmobile(umobile);
		userRegisterVo.setUname(uname);
		userRegisterVo.setPassword(password);
		// 1表示手机注册，2表示邮箱注册
		userRegisterVo.setRegisterType(1);
		userRegisterService.doRegisterByMobile(userRegisterVo);
		model.addAttribute("uid", userRegisterVo.getUid());

		// 初始化用户积分
		memberPointService.getUserMemberPoint(userRegisterVo.getUid());
		String loginDomain = BasePropertyConfigurer.getContextProperty(
				"p2p.loginDomain").toString();
		String userHomeUrl = BasePropertyConfigurer.getContextProperty(
				"p2p.userDomain").toString()
				+ "/home/index.html";
		String tokenLoginUrl = loginDomain + "/tokenlogin.html?backUrl="
				+ userHomeUrl;
		String token = umobile + "," + LoginToken.DEFAULT_SALT + ","
				+ DateUtil.getDateStr(new Date());
		String encrypedToken = Encrypter.encrypt(token);
		tokenLoginUrl += "&token=" + encrypedToken;
		return "redirect:" + tokenLoginUrl;
	}

}
